package com.example.springboot.service;

import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    public User getUserById(Integer userId) {
        return userMapper.getUserById(userId);
    }

    public void updateUsername(Integer userId, String username) {
        userMapper.updateUsername(userId, username);
    }

    public void updateAvatar(Integer userId, String avatarUrl) {
        userMapper.updateAvatar(userId, avatarUrl);
    }





    // 获取所有用户（分页，仅限超级管理员）
    public Page<User> getAllUsers(String username, int page, int size, String query) {
        if (!hasSuperRole(username)) {
            return null;
        }
        PageHelper.startPage(page, size, "created_at DESC");
        if (query != null && !query.trim().isEmpty()) {
            return userMapper.findByQuery(query);
        }
        return userMapper.getAllUsers();
    }

    // 删除用户（仅限超级管理员）
    public boolean deleteUser(Integer userId, String username) {
        if (!hasSuperRole(username)) {
            return false;
        }
        userMapper.deleteUser(userId);
        logger.info("用户 ID: {} 删除成功，由管理员 {} 操作", userId, username);
        return true;
    }

    // 添加用户（仅限超级管理员）
    public boolean addUser(User user, String username) {
        if (!hasSuperRole(username)) {
            return false;
        }
        userMapper.addUser(user);
        logger.info("用户 {} 添加成功，由管理员 {} 操作", user.getUsername(), username);
        return true;
    }

    // 更新用户（仅限超级管理员）
    public boolean updateUser(Integer userId, User user, String username) {
        if (!hasSuperRole(username)) {
            return false;
        }
        User existingUser = userMapper.getUserById(userId);
        if (existingUser == null) {
            logger.warn("用户 ID: {} 不存在，无法更新", userId);
            return false;
        }
        user.setUserId(userId); // 确保更新的是指定用户
        userMapper.updateUser(user);
        logger.info("用户 ID: {} 更新成功，由管理员 {} 操作", userId, username);
        return true;
    }

    // 获取单个用户信息（仅限超级管理员）
    public User getUserById(Integer userId, String username) {
        if (!hasSuperRole(username)) {
            return null;
        }
        User user = userMapper.getUserById(userId);
        if (user == null) {
            logger.warn("用户 ID: {} 不存在", userId);
        }
        return user;
    }

    // 检查是否为超级管理员
    private boolean hasSuperRole(String username) {
        if (username == null) {
            return false;
        }
        String role = userMapper.findRoleByUsername(username);
        return "super".equals(role);
    }
}
